﻿using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Helpers;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.presentation.nodeFactory;
using umbraco.BusinessLogic;


namespace SuperSimpleWebshop.Payment.SagePay
{
    public class SagePayPaymentRequestHandler : IPaymentRequestHandler
    {
        public bool TestModeEnabled { get; private set; }
        //VPSProtocal=2.23&TxType=PAYMENT&Vendor=#SAGEPAYVENDOR#&VendorTxCode=#REFERENCECODE#&Amount=#totalamount#&Currency=#CURRENCY#&Description=#FREETEXT#&NotificationURL=#URL#&BillingSurname=#SURNAME#&BillingFirstnames=#FIRSTNAME#&BillingAddress1=#ADDRESS#&BillingCIty=#CITY#&BillingPostCode=#POSTALCODE#&BillingCountry=#COUNTRY#&DeliverySurname=#LASTNAME#&DeliveryFirstnames="#FIRSTNAME#&DeliveryAddress1=#DeliveryADDRESS#&DeliveryCIty="#CITY#&DeliveryPostCode=#POSTALCODE#&DeliveryCountry=#COUNTRY#&CustomerMail=#EMAIL#

        #region IPaymentRequestHandler Members
        /// <summary>
        /// Gets the payment provider name
        /// </summary>
        /// <returns>Name of the payment provider</returns>
        public string GetName()
        {
            return "SagePay";
        }

        /// <summary>
        /// Creates a payment request for this payment provider
        /// </summary>
        /// <param name="order">Order to base the payment request on</param>
        /// <returns>Payment request</returns>
        public PaymentRequest CreatePaymentRequest(Order order)
        {
            var helper = new PaymentConfigHelper(order.OrderInfo.PaymentInfo.PaymentProviderName);

            //var paymentProvider = new OrderRepository().GetAllPaymentProviders().Where(x => x.Name == order.OrderInfo.PaymentInfo.PaymentModule).FirstOrDefault();
            var paymentProvider = new OrderRepository().GetAllPaymentProviders().Where(x => x.Name == order.OrderInfo.PaymentInfo.PaymentProviderName).FirstOrDefault();

            var request = new PaymentRequest();

            request.Parameters.Add("Service", "VendorRegisterTx");
            
            request.Parameters.Add("VPSProtocol", "2.23");

            request.Parameters.Add("TxType", "PAYMENT");

            // retrieve Vendor Name
            #region SagePay vendor Name
            string VendorName = "";
            if (!string.IsNullOrEmpty(helper.Settings["VendorName"]))
            {
                VendorName = helper.Settings["VendorName"];
            }
            #endregion

            request.Parameters.Add("Vendor", VendorName);

            // Set GUID to identify order in SSWS
            // Sent GUID for identification to PayPal
            // PayPal will return custom value to validate order
            order.OrderInfo.PaymentInfo.PaymentTransactionId = Guid.NewGuid().ToString();

           // request.Parameters.Add("VendorTxCode", order.OrderInfo.OrderNumber.Replace("[demo]-", ""));
            request.Parameters.Add("VendorTxCode", order.OrderInfo.PaymentInfo.PaymentTransactionId.ToString());

            CultureInfo ci = new CultureInfo("en-US");
            
            //var totalAmountAsString = OrderHelper.GetTotalAmountUsingVATCheck().ToString("N", ci);
            var totalAmountAsString = order.OrderInfo.TotalAmountWithTax.ToString("N", ci);
            request.Parameters.Add("Amount", totalAmountAsString);
            request.Parameters.Add("Currency", order.OrderInfo.ShopAlias.CurrencyCode);

            request.Parameters.Add("Description", order.OrderInfo.OrderNumber.ToString());

            var baseUrl = string.Format("http://{0}", library.GetCurrentDomains(Node.GetCurrent().Id).First().Name);
            baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));
            var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), ShopAliasHelper.GetCurrentShopAlias());

            string reportUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(paymentProvider.Id));
            request.Parameters.Add("NotificationURL", reportUrl);

            order.OrderInfo.PaymentInfo.PaymentParameterRenderMethod = PaymentParameterRenderMethod.Form;

            request.Parameters.Add("BillingSurname", order.Node.GetProperty("customerLastName").Value);
            request.Parameters.Add("BillingFirstnames", order.Node.GetProperty("customerFirstName").Value);
            request.Parameters.Add("BillingAddress1", "hidden");
            request.Parameters.Add("BillingCity", "hidden");
            request.Parameters.Add("BillingPostCode", "hidden");
            request.Parameters.Add("BillingCountry", order.Node.GetProperty("customerCountry").Value);

            request.Parameters.Add("DeliverySurname", order.Node.GetProperty("customerLastName").Value);
            request.Parameters.Add("DeliveryFirstnames", order.Node.GetProperty("customerFirstName").Value);
            request.Parameters.Add("DeliveryAddress1", "hidden");
            request.Parameters.Add("DeliveryCity", "hidden");
            request.Parameters.Add("DeliveryPostCode", "hidden");
            request.Parameters.Add("DeliveryCountry",  order.Node.GetProperty("customerCountry").Value);

            #region URLforTestMode
            // check if provider is in testmode to send request to right URL

            if (helper.TestModeEnabled)
            {
                request.PaymentUrlBase = helper.Settings["testURL"];
            }
            else
            {
                request.PaymentUrlBase = helper.Settings["url"];
            }
            #endregion

            order.OrderInfo.PaymentInfo.PaymentURL = request.PaymentUrl;
            order.OrderInfo.PaymentInfo.PaymentParameters = request.ParametersAsString;

            return request;
        }
        #endregion

    }
}